package org.example.admin.timerJob;

import com.alibaba.fastjson.JSONObject;
import org.example.admin.utils.SseEmitterUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * SseEmitter与 spring event
 */
@Component // orderJob
public class SseEmitterJob {

    public void orderProcess() {
        Map<String, Object> map = new HashMap<>();
        map.put("title", "系统通知");
        map.put("content", "abfkefjiejfaojfeoijfoe");

        String json = JSONObject.toJSONString(map);

        /**
        if(SseEmitterUtils.seMap.size() > 0) {
            SseEmitterUtils.seMap.forEach((k, v) -> {
                try {
                    v.send(json);
                    v.complete();
                } catch (IOException ioException) {  //如果出现异常，表示客户端关闭
                    SseEmitterUtils.seMap.remove(k);
//                    System.out.println(SseEmitterUtils.seMap.size());
                }
            });
        }
         */

        if(SseEmitterUtils.seMap.size() > 0) {
            SseEmitterUtils.seMap.forEach((k, v) -> {
                try {
                    v.send(SseEmitter.event().name("system_notify").data(json));
                    v.complete();
                } catch (IOException ioException) {  //如果出现异常，表示客户端关闭
                    SseEmitterUtils.seMap.remove(k);
//                    System.out.println(SseEmitterUtils.seMap.size());
                }
            });
        }

    }
}
